package com.alm.handle.mq;

import com.alm.handle.util.CacheUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.util.ReferenceCountUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
@Component
public class ProxyCommandService {
    private final Logger logger = LoggerFactory.getLogger(ProxyCommandService.class);
    //send
    public boolean send(String ctxId, String data){
        boolean flag = false;
        ChannelHandlerContext ctx = CacheUtil.ctxMap.get(ctxId);
        if(ctx == null){
            logger.info("P send failed, ctx is null");
            return false;
        }
        ByteBuf buf = Unpooled.unreleasableBuffer(Unpooled.copiedBuffer(data.getBytes()));
        try {
            if(ctx.channel().isWritable()){
                ctx.writeAndFlush(buf.duplicate());
                flag = true;
                logger.info("P send cmd to device success, ctx:{}", ctxId);
            }
        }catch(Exception e){
            logger.info("P send command exception, ctx:{}", ctxId);
            e.printStackTrace();
        }finally {
            ReferenceCountUtil.release(buf);
        }
        return flag;
    }

    //send
    public boolean sendByByte(String ctxId, byte [] data){
        boolean flag = false;
        ChannelHandlerContext ctx = CacheUtil.ctxMap.get(ctxId);
        if(ctx == null){
            logger.info("P send failed, ctx is null");
            return false;
        }
        ByteBuf buf = Unpooled.buffer(0);
        buf.writeBytes(data);
        try {
            if(ctx.channel().isWritable()){
                ctx.writeAndFlush(buf.duplicate());
                flag = true;
                logger.info("P send cmd to device success, ctx:{}", ctxId);
            }
        }catch(Exception e){
            logger.info("P send command exception, ctx:{}", ctxId);
            e.printStackTrace();
        }finally {
            ReferenceCountUtil.release(data);
        }
        return flag;
    }
}
